import { Injectable } from '@nestjs/common';
import { interfaceBooks } from './interface/books.interface';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
// 导入书籍实体类
import { Books } from './books.entity';
@Injectable()
export class BooksService {
  constructor(
    @InjectRepository(Books)
    private books: Repository<Books>,
  ) {}
  async findAll(): Promise<interfaceBooks[]> {
    return await this.books.find();
  }
  async create(
    book: interfaceBooks,
  ): Promise<{ message: string; success: boolean }> {
    const newData = this.books.create(book);
    await this.books.save(newData);
    return {
      message: 'Book created successfully',
      success: true,
    };
  }
  async update(
    params: interfaceBooks,
  ): Promise<{ message: string; success: boolean }> {
    const bookToUpdate = await this.books.findOne({
      where: { id: params.id },
    });
    if (!bookToUpdate) {
      return {
        message: 'Book not found',
        success: false,
      };
    }
    Object.assign(bookToUpdate, params);
    await this.books.save(bookToUpdate);
    return {
      message: 'Book updated successfully',
      success: true,
    };
  }
  async delete(params: {
    id: number;
  }): Promise<{ message: string; success: boolean }> {
    const bookToDelete = await this.books.findOne({
      where: { id: params.id },
    });
    if (!bookToDelete) {
      return {
        message: 'Book not found',
        success: false,
      };
    }
    await this.books.remove(bookToDelete);
    return {
      message: 'Book deleted successfully',
      success: true,
    };
  }
}
